using System.Net;

namespace Lzfy_Refund_Service.Middleware
{
    /// <summary>
    /// 企业微信访问限制中间件
    /// </summary>
    public class WeChatAccessMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configuration;
        private readonly ILogger<WeChatAccessMiddleware> _logger;

        public WeChatAccessMiddleware(
            RequestDelegate next,
            IConfiguration configuration,
            ILogger<WeChatAccessMiddleware> logger)
        {
            _next = next;
            _configuration = configuration;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 检查是否需要企业微信访问限制
            if (ShouldCheckWeChatAccess(context))
            {
                if (!await IsValidWeChatRequestAsync(context))
                {
                    _logger.LogWarning("非企业微信环境访问被拒绝: {RemoteIpAddress} {UserAgent}", 
                        context.Connection.RemoteIpAddress, 
                        context.Request.Headers.UserAgent);
                    
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    await context.Response.WriteAsync("Access denied. This application can only be accessed from WeChat Work.");
                    return;
                }
            }

            await _next(context);
        }

        /// <summary>
        /// 判断是否需要检查企业微信访问权限
        /// </summary>
        private static bool ShouldCheckWeChatAccess(HttpContext context)
        {
            var path = context.Request.Path.Value?.ToLower() ?? "";
            
            // 排除API接口、健康检查等
            var excludePaths = new[]
            {
                "/api/auth/wechatlogin",
                "/api/auth/getwechatjsapiconfig",
                "/health",
                "/swagger",
                "/favicon.ico"
            };

            return !excludePaths.Any(exclude => path.StartsWith(exclude));
        }

        /// <summary>
        /// 验证是否为有效的企业微信请求
        /// </summary>
        private async Task<bool> IsValidWeChatRequestAsync(HttpContext context)
        {
            try
            {
                // 1. 检查User-Agent是否包含企业微信标识
                var userAgent = context.Request.Headers.UserAgent.ToString();
                if (IsWeChatWorkUserAgent(userAgent))
                {
                    return true;
                }

                // 2. 检查Referer是否来自可信域名
                var referer = context.Request.Headers.Referer.ToString();
                if (IsFromTrustedDomain(referer))
                {
                    return true;
                }

                // 3. 检查IP白名单（开发环境）
                var remoteIp = context.Connection.RemoteIpAddress?.ToString() ?? "";
                if (IsAllowedIP(remoteIp))
                {
                    return true;
                }

                // 4. 检查是否有有效的企业微信Token
                if (await HasValidWeChatTokenAsync(context))
                {
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证企业微信请求时发生异常");
                return false;
            }
        }

        /// <summary>
        /// 检查User-Agent是否为企业微信
        /// </summary>
        private static bool IsWeChatWorkUserAgent(string userAgent)
        {
            if (string.IsNullOrEmpty(userAgent))
                return false;

            var wechatWorkIdentifiers = new[]
            {
                "wxwork",
                "MicroMessenger",
                "WeChatWork"
            };

            return wechatWorkIdentifiers.Any(identifier => 
                userAgent.Contains(identifier, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 检查是否来自可信域名
        /// </summary>
        private bool IsFromTrustedDomain(string referer)
        {
            if (string.IsNullOrEmpty(referer))
                return false;

            try
            {
                var uri = new Uri(referer);
                var trustedDomains = _configuration.GetSection("WeChat:TrustedDomains").Get<string[]>() ?? Array.Empty<string>();
                
                return trustedDomains.Any(domain => 
                    uri.Host.Equals(domain, StringComparison.OrdinalIgnoreCase) ||
                    uri.Host.EndsWith($".{domain}", StringComparison.OrdinalIgnoreCase));
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查IP是否在白名单中
        /// </summary>
        private bool IsAllowedIP(string remoteIp)
        {
            if (string.IsNullOrEmpty(remoteIp))
                return false;

            var allowedIPs = _configuration.GetSection("WeChat:AllowedIPs").Get<string[]>() ?? Array.Empty<string>();
            return allowedIPs.Contains(remoteIp);
        }

        /// <summary>
        /// 检查是否有有效的企业微信Token
        /// </summary>
        private async Task<bool> HasValidWeChatTokenAsync(HttpContext context)
        {
            try
            {
                // 从Authorization header或cookie中获取token
                var token = context.Request.Headers.Authorization.FirstOrDefault()?.Replace("Bearer ", "") ??
                           context.Request.Cookies["wechat_token"];

                if (string.IsNullOrEmpty(token))
                    return false;

                // 这里可以添加token验证逻辑
                // 例如：验证JWT token中是否包含企业微信用户信息
                
                return await Task.FromResult(true); // 简化实现
            }
            catch
            {
                return false;
            }
        }
    }

    /// <summary>
    /// 企业微信访问中间件扩展
    /// </summary>
    public static class WeChatAccessMiddlewareExtensions
    {
        public static IApplicationBuilder UseWeChatAccess(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<WeChatAccessMiddleware>();
        }
    }
}